<template>
  <div>
    <BaseForm
      ref="searchForm"
      type="search"
      v-model:items="formItems"
      v-model:form="searchParams"
      @search="handleSearch"
      labelWidth="120px"
    >
      <el-form-item>
        <el-radio-group v-model="dateRadio" @change="dateChange">
          <el-radio-button label="今日" />
          <el-radio-button label="昨日" />
          <el-radio-button label="本周" />
          <el-radio-button label="本月" />
          <el-radio-button label="今年" />
          <el-radio-button label="全部" />
          <el-radio-button label="自定义" />
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          style="width: 330px"
          v-model="searchParams.date"
          type="datetimerange"
          :disabled="disabledTime"
          range-separator="~"
          value-format="YYYY-MM-DD HH:ss:mm"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
        />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input style="width: 255px" v-model="searchParams.managerName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="虚拟号码">
        <el-input style="width: 255px" v-model="searchParams.virtualNumber" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="供电单位">
        <selectPage :item="powerItem" v-model="searchParams.powerId" @update:modelValue="changePower" />
      </el-form-item>
      <el-form-item label="供电线路" style="margin-left: 30px">
        <selectPage
          :item="lineItem"
          ref="LineRef"
          v-model="searchParams.lineId"
          :search="searchParams.lineSearch"
          @update:modelValue="changeLine"
        />
      </el-form-item>
      <el-form-item label="台区" style="margin-left: 30px">
        <selectPage
          ref="AreaRef"
          :item="areaItem"
          v-model="searchParams.areaId"
          :search="searchParams.areaSearch"
          @update:modelValue="changeArea"
        />
      </el-form-item>
      <el-form-item label="关联片区/村社">
        <selectPage
          :item="communityItem"
          ref="CommunityRef"
          v-model="searchParams.communityId"
          :search="searchParams.communitySearch"
        />

        <!--        <el-select style="width: 255px" v-model="searchParams.communityId" filterable placeholder="请选择" clearable>-->
        <!--          <el-option v-for="item in communityList" :key="item.value" :value="item.value" :label="item.label">-->
        <!--          </el-option>-->
        <!--        </el-select>-->
      </el-form-item>
    </BaseForm>

    <BaseTable
      ref="baseTable"
      :getTableDataFn="reportStatisticsService.robotLedgerPageList"
      :searchParams="searchParams"
      :downLoad="downLoad"
      :serial="false"
      :down="true"
      serialLabel="触发次数排名"
    >
      <el-table-column prop="managerName" label="网格经理姓名" />
      <el-table-column prop="powerNames" label="供电单位" show-overflow-tooltip> </el-table-column>
      <el-table-column prop="lineNames" label="供电线路" show-overflow-tooltip> </el-table-column>
      <el-table-column prop="areaNames" label="台区名称" show-overflow-tooltip> </el-table-column>
      <el-table-column prop="communityNames" label="关联片区/村社" minWidth="170"> </el-table-column>
      <el-table-column prop="virtualNumber" label="虚拟号码"></el-table-column>
      <el-table-column prop="managerMessageNum" label="网格经理消息数量"></el-table-column>
      <el-table-column prop="robotMessageNum" label="机器人消息数量"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click.prevent.stop="handleShowDetail(scope.row)">查看消息详情</el-button>
        </template>
      </el-table-column>
    </BaseTable>

    <el-dialog title="消息详情" width="1000" v-model="state.visible">
      <BaseForm
        ref="modalForm"
        type="search"
        v-model:items="state.formItems"
        v-model:form="state.modalParams"
        @search="handleModalSearch"
        labelWidth="120px"
      >
        <el-form-item label="机器人">
          <el-select v-model="state.modalParams.robotId" placeholder="">
            <el-option v-for="item in robotList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </BaseForm>
      <BaseTable
        ref="modalTable"
        :getTableDataFn="basicConfigService.pageListManagerAndRobotMessage"
        :searchParams="state.modalParams"
        :downLoad="downLoadMessage"
        :serial="false"
        :down="true"
      >
        <el-table-column prop="sendUserName" label="消息发送人" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="recordTime" label="消息发送时间" width="180"></el-table-column>
        <el-table-column prop="recordContent" label="消息内容">
          <template #default="scope">
            <el-tooltip placement="top" popper-class="tooltip-width">
              <template #content>
                <div style="max-width: 590px; overflow: auto">
                  <pre>{{ scope.row.recordContent }}</pre>
                </div>
              </template>
              <div style="width: 590px; overflow: auto">
                <pre>{{ scope.row.recordContent }}</pre>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
      </BaseTable>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import SortTable from '@/components/sortTable.vue';
import { basicConfigService } from '@/api/basicConfig';
import { reportStatisticsService } from '@/api/reportStatistics';
import { commonService } from '@/api/common';
const modalTable = ref('modalTable');
const cateList = ref([]);
import moment from 'moment';
const dateRadio = ref('今日');
const item = ref({});
const visibleGroupChat = ref(false);
const dateChange = (val) => {
  switch (val) {
    case '今日':
      searchParams.value.recordTimeBegin = moment().format('yyyy-MM-DD 00:00:00');
      searchParams.value.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59');
      state.modalParams.recordTimeBegin = moment().format('yyyy-MM-DD 00:00:00');
      state.modalParams.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59');
      break;
    case '昨日':
      searchParams.value.recordTimeBegin = moment().subtract(1, 'days').format('yyyy-MM-DD 00:00:00');
      searchParams.value.recordTimeEnd = moment().subtract(1, 'days').format('yyyy-MM-DD 23:59:59');
      state.modalParams.recordTimeBegin = moment().subtract(1, 'days').format('yyyy-MM-DD 00:00:00');
      state.modalParams.recordTimeEnd = moment().subtract(1, 'days').format('yyyy-MM-DD 23:59:59');
      break;
    case '本周':
      searchParams.value.recordTimeBegin = moment().weekday(1).format('yyyy-MM-DD 00:00:00');
      searchParams.value.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59');
      state.modalParams.recordTimeBegin = moment().weekday(1).format('yyyy-MM-DD 00:00:00');
      state.modalParams.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59');
      break;
    case '本月':
      searchParams.value.recordTimeBegin = moment().format('yyyy-MM-01 00:00:00');
      searchParams.value.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59');
      state.modalParams.recordTimeBegin = moment().format('yyyy-MM-01 00:00:00');
      state.modalParams.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59');
      break;
    case '今年':
      searchParams.value.recordTimeBegin = moment().format('yyyy-01-01 00:00:00');
      searchParams.value.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59');
      state.modalParams.recordTimeBegin = moment().format('yyyy-01-01 00:00:00');
      state.modalParams.recordTimeEnd = moment().format('yyyy-MM-DD 23:59:59');
      break;
    case '全部':
      searchParams.value.recordTimeBegin = undefined;
      searchParams.value.recordTimeEnd = undefined;
      state.modalParams.recordTimeBegin = undefined;
      state.modalParams.recordTimeEnd = undefined;
      break;
    default:
      return;
  }
  handleSearch();
};
const sortTablekey = ref(0);
const isDesc = ref(null);
const handleSort = (e) => {
  sortTablekey.value = e;
};
const disabledTime = computed(() => dateRadio.value !== '自定义');
const formItems = ref([
  /*  {
         name: '',
         key: 'date',
         type: 'datetimerange',
         placeholder: '选择时间范围',
         disabled: computed(() => dateRadio.value !== '自定义'),
     },

     {
         name: '微信名称',
         key: 'opinionKey',
         clearable: true,
         type: 'input',
     }, */
]);

const state = reactive({
  visible: false,
  robotSearch: {
    managerType: 2,
  },
  robotItem: {
    name: '机器人',
    key: 'managerId',
    funName: 'getAllRobot',
    option: {
      name: 'managerName',
      value: 'managerId',
    },
  },
  modalParams: {
    managerWxId: '',
    robotId: '',
    recordTimeBegin: moment().format('yyyy-MM-DD 00:00:00'),
    recordTimeEnd: moment().format('yyyy-MM-DD 23:59:59'),
  },
  formItems: [],
});
const powerItem = ref({
  name: '供电单位',
  key: 'powerId',
  funName: 'getByAreaQueryByPower',
  option: {
    name: 'powerName',
    value: 'powerId',
  },
});

const lineItem = ref({
  name: '供电线路',
  key: 'lineId',
  funName: 'getByAreaQueryByLine',
  option: {
    name: 'lineName',
    value: 'lineId',
  },
});

const areaItem = ref({
  name: '台区',
  key: 'areaId',
  funName: 'getByAreaQueryByArea',
  option: {
    name: 'areaName',
    value: 'areaId',
  },
});

const communityItem = ref({
  name: '关联片区/村社',
  key: 'communityId',
  funName: 'getAllCommunity',
  option: {
    name: 'communityName',
    value: 'communityId',
  },
});

const searchParams = ref({
  managerName: '',
  virtualNumber: '',
  powerId: '',
  lineId: '',
  areaId: '',
  communityId: '',
  recordTimeBegin: moment().format('yyyy-MM-DD 00:00:00'),
  recordTimeEnd: moment().format('yyyy-MM-DD 23:59:59'),
  date: [],

  //临时变量
  lineSearch: {
    powerId: '',
  },
  areaSearch: {
    powerId: '',
    lineId: '',
  },
  communitySearch: {
    powerId: '',
    lineId: '',
    areaId: '',
  },
});

const changePower = (val: any) => {
  //线路搜索
  searchParams.value.lineSearch.powerId = val;
  //台区搜索赋值
  searchParams.value.areaSearch.powerId = val;
  searchParams.value.areaSearch.lineId = '';

  //社区搜索赋值
  searchParams.value.communitySearch.powerId = val;
  searchParams.value.communitySearch.lineId = '';
  searchParams.value.communitySearch.areaId = '';

  //公共搜索
  searchParams.value.lineId = '';
  searchParams.value.areaId = '';
  searchParams.value.communityId = '';
};
const changeLine = (val: any) => {
  searchParams.value.areaSearch.lineId = val;

  searchParams.value.communitySearch.lineId = val;
  searchParams.value.communitySearch.areaId = '';

  searchParams.value.areaId = '';
  searchParams.value.communityId = '';
};

const changeArea = (val: any) => {
  searchParams.value.communitySearch.areaId = val;

  searchParams.value.communityId = '';
};

const baseTable = ref(null);
const handleSearch = (data = { sort: undefined }, e = '') => {
  if (e != 'sort') sortTablekey.value = 0;
  if (data) isDesc.value = data.sort;
  else {
    isDesc.value = null;
  }
  if (data == null) {
    dateRadio.value = '今日';
    searchParams.value.typeId = '';
  }
  const date = searchParams.value.date;
  if (dateRadio.value === '自定义') {
    searchParams.value.recordTimeBegin = date[0] || undefined;
    searchParams.value.recordTimeEnd = date[1] || undefined;
  } else {
    searchParams.value.date = [];
  }
  setTimeout(() => {
    baseTable.value.handleSearch({
      ...searchParams.value,
      orderField: sortTablekey.value,
      isDesc: data?.sort,
      date: undefined,
    });
  });
};

const downLoadMessage = () => {
  reportStatisticsService
    .robotLedgerPageListDetailDownload({
      data: {
        ...state.modalParams,
      },
    })
    .then((res) => {
      var blob = new Blob([res]);
      let url = window.URL.createObjectURL(blob);
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', '网格经理私聊机器人台账-消息详情.xls');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
};
const downLoad = () => {
  reportStatisticsService
    .robotLedgerPageListDownload({
      data: {
        ...searchParams.value,
        orderField: sortTablekey.value,
        isDesc: isDesc.value,
        date: undefined,
      },
    })
    .then((res) => {
      var blob = new Blob([res]);
      let url = window.URL.createObjectURL(blob);
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', '网格经理私聊机器人台账.xls');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
};
const getListByParentKey = () => {
  commonService.getListByParentKey({ data: 'cruxKeyManager' }).then((res) => {
    let data = res.data.map((e) => {
      return {
        label: e.dictionaryName,
        value: e.dictionaryValue,
      };
    });
    cateList.value.push(...data);
  });
};
const openGroupChat = (row) => {
  item.value = { ...row };
  visibleGroupChat.value = true;
};
// const communityList = ref([]);
// const getAllCommunity = () => {
//   basicConfigService.getAllCommunity({ data: {} }).then((res) => {
//     let data = res.data.map((e) => {
//       return {
//         label: e.communityName,
//         value: e.communityId,
//       };
//     });
//     communityList.value.push(...data);
//   });
// };

const optionsMange = ref([]);
const getAllManager = () => {
  basicConfigService.getAllManager({ data: {} }).then((res) => {
    optionsMange.value = res.data.map((n) => {
      return {
        label: n.managerName,
        value: n.managerId,
      };
    });
  });
};

onMounted(() => {
  getListByParentKey();
  getAllRobot();
  // console.log(state.modalParams, 'state.modalParams');
});

const handleShowDetail = (row: any) => {
  state.visible = true;
  state.modalParams.managerWxId = row.wxId;
  state.modalParams.recordTimeBegin = searchParams.value.recordTimeBegin;
  state.modalParams.recordTimeEnd = searchParams.value.recordTimeEnd;
  handleModalSearch();
};

const handleModalSearch = () => {
  state.modalParams.recordTimeBegin = searchParams.value.recordTimeBegin;
  state.modalParams.recordTimeEnd = searchParams.value.recordTimeEnd;
  // 弹窗搜索
  setTimeout(() => {
    modalTable.value.handleSearch({
      ...state.modalParams,
    });
  }, 500);
};

// 获取所有机器人列表
const robotList: any = ref([]);
const getAllRobot = async () => {
  const res = await basicConfigService.getAllRobot({ data: {} });
  if (res.success) {
    res.data.forEach((item) => {
      robotList.value.push({
        label: item.managerName,
        value: item.managerId,
      });
    });
  }
};
const changeRobot = (val) => {
  console.log(val, 'val');
};
</script>

<style lang="scss">
:deep(.el-date-editor) {
  padding: 1px 10px;
}
.tooltip-width {
  width: 1000px;
}
</style>
